//
//  BargainViewController.m
//  quxiangtao
//
//  Created by E人一铺 on 2019/2/27.
//  Copyright © 2019年 shanhaijin. All rights reserved.
//

#import "BargainViewController.h"
#import "BargainTableViewModel.h"
#import "BargainTableViewCell.h"

@interface BargainViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (strong, nonatomic) UITableView *gooodsTableView;

@property (assign, nonatomic) NSInteger page;

@property (strong, nonatomic) NSMutableArray *orderArr;

@end

@implementation BargainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor clearColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    self.page = 1;
    
    [self.view addSubview:self.gooodsTableView];
    __weak typeof(self) weakSelf = self;
    [self.gooodsTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(weakSelf.view.mas_left);
        make.right.mas_equalTo(weakSelf.view.mas_right);
        make.top.mas_equalTo(weakSelf.view.mas_top);
        make.bottom.mas_equalTo(weakSelf.view.mas_bottom);
    }];
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    [header beginRefreshing];
    [header setTitle:@"下拉可以刷新!" forState:MJRefreshStateIdle];
    [header setTitle:@"松手立即刷新!" forState:MJRefreshStatePulling];
    [header setTitle:@"正在加载..." forState:MJRefreshStateRefreshing];
    header.stateLabel.font = Font(24);
    header.backgroundColor = [UIColor clearColor];
    [header setTintColor:[UIColor clearColor]];
    
    header.stateLabel.textColor = Color999999;
    header.lastUpdatedTimeLabel.hidden = YES;
    self.gooodsTableView.mj_header = header;
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    [footer setTitle:@"" forState:MJRefreshStateIdle];
    [footer setTitle:@"正在加载。。。。" forState:MJRefreshStateRefreshing];
    [footer setTitle:@"没有更多数据！" forState:MJRefreshStateNoMoreData];
    footer.stateLabel.font = Font(17);
    footer.stateLabel.textColor = Color999999;
    self.gooodsTableView.mj_footer = footer;
    self.gooodsTableView.mj_footer.hidden = NO;
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(goodsConfirmReceipt:) name:@"NSConfirmReceiptNotification" object:nil];
}

- (void)goodsConfirmReceipt:(NSNotification *)notification {
    
    NSDictionary *dict = notification.object;
    
    [self.orderArr removeObject:dict[@"model"]];
    
    [self.gooodsTableView reloadData];
    
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark 下拉刷新数据
- (void)loadNewData
{
    
    self.page = 1;
    
    [self.gooodsTableView.mj_footer resetNoMoreData];
    [self loadData];
    
    [self.gooodsTableView reloadData];
    
    // 拿到当前的下拉刷新控件，结束刷新状态
    [self.gooodsTableView.mj_header endRefreshing];
    
}

- (void)loadMoreData {
    
    self.page ++;
    
    [self loadData];
    // 刷新表格
    [self.gooodsTableView reloadData];
    // 拿到当前的上拉刷新控件，结束刷新状态
    [self.gooodsTableView.mj_footer endRefreshing];
    
}

- (void)loadData {
    self.gooodsTableView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"noData"
                                                                  titleStr:@"暂无数据"
                                                                 detailStr:@""];

    __weak typeof(self) weakSelf = self;
    
    [BargainTableViewModel buyOrderContentModelWithPage:self.page buyType:self.tradeType successBlock:^(id responseObject) {
        
        if ([responseObject[@"code"] integerValue] == 1) {
            
            NSArray *arr = responseObject[@"data"];
            
            if (arr.count > 0 || weakSelf.orderArr.count > 0 ) {
                
                weakSelf.gooodsTableView.hidden = NO;
                
                if (self.page == 1) {
                    
                    weakSelf.orderArr = (NSMutableArray *)arr;
                    
                }else {
                    
                    [weakSelf.orderArr addObjectsFromArray:arr];
                    
                }
                
                [weakSelf.gooodsTableView reloadData];
                
                if (self.page > 1 && arr.count == 0) {
                    
                    [self.gooodsTableView.mj_footer endRefreshingWithNoMoreData];
                }
                
                // 滚动cell
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:(self.page - 1) * 10];
                
                [weakSelf.gooodsTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
                
            }else {
                
                weakSelf.gooodsTableView.hidden = YES;
                                
            }
            
        }else  {
            if ([responseObject[@"code"] integerValue] == 2) {
                if (self.orderArr.count > 0) {
                    [self.orderArr removeAllObjects];
                    [self.gooodsTableView reloadData];
                }
                
            }
            [[KYAlertView sharedInstance] showAlertViewWithMessage:responseObject[@"msg"]];
            
        }
        
        
    } failBlock:^(NSError *error) {
        
        if (error) {
            
            [[KYAlertView sharedInstance] showAlertViewWithMessage:Tip];
        }
    }];
    
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return jisuanH(340);
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
//    self.gooodsTableView.estimatedRowHeight = jisuanH(340);
//
//    self.gooodsTableView.rowHeight = UITableViewAutomaticDimension;
//    return self.gooodsTableView.rowHeight;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 10;
    }
    return 0.01;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];

    BargainTableViewModel *model = self.orderArr[indexPath.section];
    
    
    
    WebViewController *vc = [[WebViewController alloc] init];
    vc.title = @"详情";
    vc.url = [NSString stringWithFormat:@"%@%@?bargain_id=%@&userid=%@&type=1", ebaseH5,@"bargain.html", model.bargain_id, [CommonUserInfo sharedInstance].user_id];
    
    if (vc) {
        
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}

#pragma mark -delegate\datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.orderArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 1;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
  
    static NSString *FSBaseTopTableViewCellIdentifier = @"BargainTableViewCell";
    
    BargainTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:FSBaseTopTableViewCellIdentifier];
    
    BargainTableViewModel *model = self.orderArr[indexPath.section];
    cell.model = model;
    cell.refundBtn.tag = indexPath.section;
    cell.showPictureBtn.tag = indexPath.section;
    
  if ([model.share_status intValue] == 1 || [model.share_status intValue] == 2 || [model.share_status intValue] == 4){
        [cell.showPictureBtn setTitleColor:[UIColor colorWithHexString:@"ff2741"] forState:UIControlStateNormal];
        cell.lineView.backgroundColor = [UIColor colorWithHexString:@"ff2741"];
    }else{
        [cell.showPictureBtn setTitleColor:Color999999 forState:UIControlStateNormal];
        cell.lineView.backgroundColor = Color999999;
    }
    [cell.showPictureBtn addTarget:self action:@selector(showPictureBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [cell.refundBtn addTarget:self action:@selector(refundBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
    
}

#pragma mark --- TOUCH
//退款
-(void)refundBtnClick:(UIButton *)sender{
    BargainTableViewModel *model = self.orderArr[sender.tag];

    WebViewController *vc = [[WebViewController alloc] init];
    if ([model.is_refund intValue] == 0) {
        
        vc.title = @"退款";
        vc.url = [NSString stringWithFormat:@"%@%@?ddid=%@&typr=1&userid=%@", ebaseH5,@"refund.html", model.ddid,[CommonUserInfo sharedInstance].user_id];

    }else{
        vc.title = @"退款";
        vc.url = [NSString stringWithFormat:@"%@%@?ddid=%@&typr=1&userid=%@", ebaseH5,@"ddcl.html", model.ddid,[CommonUserInfo sharedInstance].user_id];
        
    }
    
    if (vc) {
        __weak typeof(self) weakSelf = self;
        [vc setRefreBlock:^(NSString *fromType) {
            if ([fromType intValue] == 0) {
                [weakSelf loadNewData];
            }
        }];
        
        [self.navigationController pushViewController:vc animated:YES];
    }
}
//点击晒图
-(void)showPictureBtnClick:(UIButton *)sender{
    BargainTableViewModel *model = self.orderArr[sender.tag];
    if ([model.share_status intValue] == 1 || [model.share_status intValue] == 2 || [model.share_status intValue] == 4){
        
        WebViewController *vc = [[WebViewController alloc] init];
        vc.title = @"点击晒图";
        vc.url = [NSString stringWithFormat:@"%@%@?ddid=%@&where=bargain&bargain_id=%@&userid=%@", ebaseH5,@"blueprint.html", model.ddid, model.bargain_id,[CommonUserInfo sharedInstance].user_id];
        //[RSA encryptString:[CommonUserInfo sharedInstance].user_id publicKey:PublicKey]
        
        if (vc) {
            [self.navigationController pushViewController:vc animated:YES];
        }
    }else{
        
        
    }
    
    
}
    

#pragma mark -lazy
- (UITableView *)gooodsTableView {
    
    if (!_gooodsTableView) {
        
        _gooodsTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        
        _gooodsTableView.delegate = self;
        _gooodsTableView.dataSource = self;
        _gooodsTableView.backgroundColor = [UIColor clearColor];
        _gooodsTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _gooodsTableView.showsVerticalScrollIndicator = NO;
        _gooodsTableView.showsHorizontalScrollIndicator = NO;
        
        _gooodsTableView.estimatedSectionHeaderHeight = 5;
        _gooodsTableView.estimatedSectionFooterHeight = 0;
        _gooodsTableView.estimatedRowHeight = 0;
        
        [_gooodsTableView registerNib:[UINib nibWithNibName:@"BargainTableViewCell" bundle:nil] forCellReuseIdentifier:@"BargainTableViewCell"];
        
        
        if (@available(iOS 11.0, *)) {
            
            _gooodsTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            
        }
        
    }
    
    return _gooodsTableView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
